'use strict'

const Service = require('egg').Service
const moment = require('moment')

class DeviceService extends Service {
  async getDeviceList(queryInfo) {
    // 验证query Info是否需要返回默认对象
    // queryInfo = this.ctx.getDefaultQueryInfo(queryInfo)

    // 初始化 queryInfo 处理未传参数情况
    queryInfo = {
      keywords: queryInfo.keywords || '',
      department_id: queryInfo.department_id || 0,
      pageNum: queryInfo.pageNum || 1,
      pageSize: queryInfo.pageSize || 10,
    }

    // 条件字符串
    let optionsStr = ''
    // 条件数组
    let optoinsArr = []

    // 选择所有部门
    if (queryInfo.department_id === '0') {
      optionsStr = ` WHERE d.device_name like ? `
      optoinsArr = ['%' + queryInfo.keywords + '%']
    } else {
      // 选择确定部门
      optionsStr = ` WHERE d.device_name like ? 
      and d.device_department_id = ?`
      optoinsArr = [
        '%' + queryInfo.keywords + '%',
        parseInt(queryInfo.department_id),
      ]
    }

    const sqlStrAll =
      `SELECT * FROM c_device AS d,c_department AS p` +
      optionsStr +
      ` AND d.device_department_id = p.id`

    let resultAll = await this.app.mysql.query(sqlStrAll, [...optoinsArr])

    let sqlStr =
      `SELECT
      d.device_id,
      d.device_name,
      d.device_model,
      d.device_manufacturer,
      d.device_date_production,
      d.device_date_service,
      d.device_date_update,
      d.device_count,
      d.device_type,
      d.device_department_id,
      p.departname,
      d.device_position,
      d.device_status,
      d.device_flaw,
      d.device_suggest,
      d.device_tips,
      d.device_manager 
    FROM
      c_device AS d
      LEFT JOIN c_department AS p ON d.device_department_id = p.id ` +
      optionsStr +
      ` LIMIT ?,?`

    let result = await this.app.mysql.query(sqlStr, [
      ...optoinsArr,
      parseInt(queryInfo.pageNum - 1) * queryInfo.pageSize,
      parseInt(queryInfo.pageSize),
    ])

    return this.ctx.getRESTfulData(
      {
        total: resultAll.length,
        deviceList: result,
      },
      '获取筛选设备列表成功',
      200
    )
  }
  async getSingleDevice(options) {
    let result = await this.app.mysql.select('c_device', {
      where: options,
    })
    return this.ctx.getRESTfulData(result, '获取单个设备成功', 200)
  }
  async createDevice(deviceInfo) {
    const result = await this.app.mysql.insert('c_device', {
      ...deviceInfo,
    })

    if (result.affectedRows === 1) {
      const singleResult2 = await this.getSingleDevice({
        device_id: result.insertId,
      })

      return this.ctx.getRESTfulData(singleResult2.data[0], '新增设备成功', 201)
    } else {
      return this.ctx.getRESTfulData(null, '新增设备失败', 401)
    }
  }
  async createManyDevice(deviceList) {
    try {
      // 记录成功条数
      let successNum = 0
      // 记录未成功信息
      let failedList = []

      for (const key in deviceList) {
        if (deviceList.hasOwnProperty(key)) {
          const item = deviceList[key]

          // 搜索到 dapartname 对应的 id
          const departResult = await this.ctx.service.managerrecord.department.getSingleDepartment(
            {
              departname: item.departname,
            }
          )

          // 删除 不能插入到该表的 字段
          delete item.departname

          // 将运行状态的 正常，异常，转换为 0，1
          item.device_status = item.device_status === '正常' ? 0 : 1
          // 将日期转换为时间戳
          item.device_date_production =
            moment(item.device_date_production).unix() * 1000
          item.device_date_service =
            moment(item.device_date_service).unix() * 1000
          item.device_date_update =
            moment(item.device_date_update).unix() * 1000

          const result = await this.app.mysql.insert('c_device', {
            ...item,
            device_department_id: departResult.data[0].id,
          })
          if (result.affectedRows === 1) {
            successNum++
          }
        }
      }

      return this.ctx.getRESTfulData(
        {
          failedList,
        },
        `设备批量添加成功: ${successNum} 条，失败：${failedList.length} 条`,
        201
      )
    } catch (error) {
      console.log(error)
      return this.ctx.getRESTfulData({ error }, '添加出错', 401)
    }
  }
  async updateDevice(deviceInfo, id) {
    delete deviceInfo.departname
    let result = await this.app.mysql.update('c_device', deviceInfo, {
      where: {
        device_id: id,
      },
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '设备更新成功',
          status: 201,
        },
      }
    }
  }
  async deleteDevice(id) {
    let result = await this.app.mysql.delete('c_device', {
      device_id: id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '设备删除成功',
          status: 200,
        },
      }
    }
  }
}

module.exports = DeviceService
